<?php
namespace App\Api\Controllers\Pay;


use App\Models\Ad;
use App\Models\AppLogo;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class BaseController extends \App\Api\Controllers\BaseController
{
    // 表单提交字符集编码
    public $postCharset = "UTF-8";
    private $fileCharset = "UTF-8";
    public $key = "88888888";
    public $yhc_key = "FA217EE7D519894FD66BA660FFD3E5BE";
    public $needpage = false; //默认不要分页

    public $l = 15;
    public $p = 1;
    public $t = 0;

    public $status = 1;
    public $message = 'ok';


    //处理完返回
    public function return_json_data($data)
    {
        $key = $this->key;
        $string = $this->getSignContent($data) . '&key=' . $key;
        $data['sign'] = md5($string);
        $data['ad_data'] = json_decode($data['ad_data'], true);

        return json_encode($data);
    }
    
     //处理完返回
    public function return_yhcdata($data)
    {
        $yhc_key = $this->yhc_key;
        $string = $this->getSignContent($data) . '&key=' . $yhc_key;
        $data['sign'] = strtoupper(md5($string));
        return response()->json($data);
    }


    //处理完返回
    public function return_data($data)
    {
        $key = $this->key;
        $string = $this->getSignContent($data) . '&key=' . $key;
        $data['sign'] = md5($string);

        return response()->json($data);
    }
    

    //有data 无分页的返回
    public function data_return($sign_data, $data, $data_a = "")
    {
        //去除data加签名
        $key = $this->key;
        $string = $this->getSignContent($sign_data) . '&key=' . $key;
        $sign_data['sign'] = md5($string);
        $sign_data['data'] = $data;
        if ($data_a) {
            $sign_data['data_a'] = $data_a;
        }
	
        return response()->json($sign_data);
    }
    

    //校验md5
    public function check_md5($data)
    {
        try {
            $key = $this->key;
            $sign = $data['sign'];
            $data['sign'] = null;
            $string = $this->getSignContent($data) . '&key=' . $key;
            if ($sign == md5($string)) {
                return [
                    'return_code' => 'SUCCESS',
                    'return_msg' => '验证通过'
                ];
            } else {
                return [
                    'return_code' => 'FALL',
                    'return_msg' => '验证不通过'
                ];
            }
        } catch (\Exception $ex) {
            return [
                'return_code' => 'FALL',
                'return_msg' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }
    
    //萤火虫校验md5
    public function check_yhcmd5($data)
    {
        try {
            $yhc_key = $this->yhc_key;
            $sign = $data['sign'];
            $data['sign'] = null;
            $string = $this->getSignContent($data) . '&key=' . $yhc_key;
            if ($sign == strtoupper(md5($string))) {
                return [
                    'return_code' => 'SUCCESS',
                    'return_msg' => '验证通过'
                ];
            } else {
                return [
                    'return_code' => 'FALL',
                    'return_msg' => '验证不通过'
                ];
            }
        } catch (\Exception $ex) {
            return [
                'return_code' => 'FALL',
                'return_msg' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //参数拼接
    public function getSignContent($params)
    {
        ksort($params);

        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }

        unset ($k, $v);
        return $stringToBeSigned;
    }


    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = $this->fileCharset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }

        return $data;
    }


    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value)
    {
        if (!isset($value)) return true;
        if ($value === null) return true;
        if (trim($value) === "") return true;

        return false;
    }


    /**
     * curl发送数据
    */
    static function curl($data, $url)
    {
        //启动一个CURL会话
        $ch = curl_init();
        // 设置curl允许执行的最长秒数
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // 获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //发送一个常规的POST请求。
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        //要传送的所有数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        // 执行操作
        $res = curl_exec($ch);
        $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($res == NULL) {
            curl_close($ch);
            return false;
        } else if ($response != "200") {
            curl_close($ch);
            return false;
        }
        curl_close($ch);
        return $res;
    }


    function curl_get($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url); //设置选项，包括URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch); //执行并获取HTML文档内容

        curl_close($ch); //释放curl句柄

        return $output;
    }


    /**
     * 校验必填字段
     */
    public function check_required($check, $data)
    {
        $rules = [];
        $attributes = [];

        foreach ($data as $k => $v) {
            $rules[$k] = 'required';
            $attributes[$k] = $v;
        }

        $messages = [
            'required' => ':attribute不能为空'
        ];
        $validator = Validator::make($check, $rules, $messages, $attributes);
        $message = $validator->getMessageBag();

        return $message->first();
    }


    public function format($cin = [])
    {
        $data = [
//            'l' => $this->l, //每页显示多少条
//            'p' => $this->p, //当前页
//            't' => $this->t, //当前页
            'status' => $this->status,
            'message' => $this->message,
            'data' => $cin
        ];

        if ($this->needpage) {
            $data['l'] = $this->l;
            $data['p'] = $this->p;
            $data['t'] = $this->t;
        }

        return response()->json($data);
    }


    /**
     * 返回分页数据
     * @param $obj
     * @param string $request
     * @return mixed
     */
    public function page($obj, $request = '')
    {
        if (empty($request)) $request = app('request');

        $this->p = abs(trim($request->get('p', 1)));
        $this->l = abs(trim($request->get('l', 15)));
        $this->needpage = true;

        $start = abs(($this->p - 1) * $this->l);

        return $obj->offset($start)->limit($this->l);
    }


    //循环获取下级的用户id
    public function getSubIds($userID, $includeSelf = true, $t1 = "", $t2 = "")
    {
        $userIDs = [$userID];
        $where = [];

        if ($t2 == "") {
            $t2 = date('Y-m-d H:i:s', time());
        }

        if ($t1) {
            $where[] = ['created_at', '>=', $t1];
            $where[] = ['created_at', '<=', $t2];
        }

        while (true) {
            //注意下不能走读地址
            $subIDs = User::whereIn('pid', $userIDs)
                ->where($where)
                ->select('id')->get()
                ->toArray();
            $subIDs = array_column($subIDs, 'id');
            $userCount = count($userIDs);
            $userIDs = array_unique(array_merge($userIDs, $subIDs));
            if ($userCount == count($userIDs)) {
                break;
            }
        }

        if (!$includeSelf) {
            for ($i = 0; $i < count($userIDs); ++$i) {
                if ($userIDs[$i] == $userID) {
                    array_splice($userIDs, $i, 1);
                    break;
                }
            }
        }

        return $userIDs;
    }


    public function ad_data($data)
    {
        try {
            $i = [1, 2, 3, 4];
            //广告部分
            $users = [];
            //配置ID-广告
            $user_id = $data['user_id'];//商户直属的业务员
            $user_id_abc = $data['user_id'];
            $store_key_id = $data['store_key_id'];
            $ad_p_id = $data['ad_p_id'];

            foreach ($i as $k => $v) {
                $user = User::where('id', $user_id_abc)
                    ->select('id', 'pid')
                    ->first();
                if ($user) {
                    $users[$k]['user_id'] = $user->id;
                    $user_id_abc = $user->pid;
                }
            }

            $e_time = date('Y-m-d H:i:s', time());
            $ad = Ad::whereIn('user_ids', $users)
                ->where('e_time', '>', $e_time)
                ->where('s_time', '<', $e_time)
                ->where('ad_p_id', $ad_p_id)
                ->orderBy('updated_at', 'desc')
                ->get();
            if ($ad->isEmpty()) {
                $ad = Ad::whereIn('created_id', $users)
                    ->where('e_time', '>', $e_time)
                    ->where('s_time', '<', $e_time)
                    ->where('ad_p_id', $ad_p_id)
                    ->orderBy('updated_at', 'desc')
                    ->get();
            }

            $i = 0;
            $j = 0;
            $ad_data1 = [];
            $ad_data2 = [];

            $logo_obj = AppLogo::where('config_id', '1234')
                ->select('ali_ad_default', 'wechat_ad_default')
                ->orderBy('updated_at', 'desc')
                ->first();
            if ($logo_obj) {
                if (in_array($ad_p_id, [1, 3, 8])) {
                    $logo_obj_url = $logo_obj->ali_ad_default;
                } else {
                    $logo_obj_url = $logo_obj->wechat_ad_default;
                }
            } else {
                $logo_obj_url = url('/ad1.png');
            }


            if (!$ad->isEmpty()) {
                foreach ($ad as $k => $value) {
                    $store_key_ids = $value->store_key_ids;
                    if ($store_key_ids) {
                        //设置门店ID
                        //查看此门店ID是否在这个里面
                        $store_key_ids_arr = explode(',', $store_key_ids);
                        if (!in_array($store_key_id, $store_key_ids_arr)) {
                            continue;
                        }
                    }

                    //范围是否设置代理商
                    $user_ids = $value->user_ids;
                    //设置代理 针对
                    if ($user_ids) {
                        //设置代理ID
                        //查看此代理ID是否在这个里面
                        $user_ids_arr = explode(',', $user_ids);
                        if (!in_array($user_id, $user_ids_arr)) {
                            continue;
                        }
                    } //没有设置代理 针对所有
                    else {
                        //查看这个广告的创建者ID是谁 获取到他下面到所有代理商ID
                        $created_id = $value->created_id;
                        $user_ids_arr = $this->getSubIds($created_id);
                        if (!in_array($user_id, $user_ids_arr)) {
                            continue;
                        }
                    }

                    $imgs = json_decode($value->imgs, true);
                    $videos = json_decode($value->videos, true);
                    $ad_file_end = "";
                    $ad_url_end = "";

                    //图片
                    foreach ($imgs as $k1 => $v1) {
//                    $i = $k + $k1;
                        $ad_data1[$i]['ad_file'] = $v1['img_url'];
                        $ad_data1[$i]['ad_url'] = $v1['click_url'];
                        $ad_data1[$i]['type'] = 'img';
                        $ad_file_end = $v1['img_url'];
                        $ad_url_end = $v1['click_url'];
                        $i += 1;
                    }

                    //视频
                    foreach ($videos as $k2 => $v2) {
//                    $i = $k + 1 + $k2;
                        $ad_data2[$j]['ad_file'] = $v2['img_url'];
                        $ad_data2[$j]['ad_url'] = $v2['click_url'];
                        $ad_data2[$j]['type'] = 'video';
                        $j += 1;
                    }

                    //再加图片
//                if ($ad_file_end) {
//                    $ad_data2[$i + 1]['ad_file'] = $ad_file_end;
//                    $ad_data2[$i + 1]['ad_url'] = $ad_url_end;
//                }
                }

                $ad_data = array_merge($ad_data1, $ad_data2);
                if (empty($ad_data)) {
                    $ad_data = [
                        [
                            'ad_file' => $logo_obj_url,
                            'ad_url' => url('/mb/login'),
                            'type' => 'img'
                        ]
                    ];
                }
            } else {
                $ad_data = [
                    [
                        'ad_file' => $logo_obj_url,
                        'ad_url' => url('/mb/login'),
                        'type' => 'img'
                    ]
                ];
            }

            return $ad_data;
        } catch (\Exception $ex) {
            Log::info('设备广告error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            $this->status = -1;
            $this->message = $ex->getMessage().' | '.$ex->getLine();
            return $this->format();
        }
    }


}
